package com.authine.cloudpivot.ext.applicationservice;

import com.alibaba.cola.dto.RequestContext;
import com.alibaba.cola.dto.SingleResponse;
import com.alibaba.cola.exception.BizException;
import com.alibaba.fastjson.JSON;
import com.authine.cloudpivot.ext.constants.AppConst;
import com.authine.cloudpivot.ext.constants.ErrorCodeConst;
import com.authine.cloudpivot.ext.constants.ModelConst;
import com.authine.cloudpivot.ext.dto.TreeData;
import com.authine.cloudpivot.ext.dto.kingDee.request.KingDeeCancelPayment;
import com.authine.cloudpivot.ext.dto.kingDee.request.KingDeeRequestPayment;
import com.authine.cloudpivot.ext.dto.kingDee.request.KingDeeRequestPaymentDetail;
import com.authine.cloudpivot.ext.dto.system.UserDto;
import com.authine.cloudpivot.ext.dto.transfer.TransferConfirmPaymentDto;
import com.authine.cloudpivot.ext.dto.transfer.UpdateConfirmTimeDto;
import com.authine.cloudpivot.ext.enums.kingdee.KingDeePaymentApplyType;
import com.authine.cloudpivot.ext.enums.order.transfer.MemberPurchaseOrderEnum;
import com.authine.cloudpivot.ext.enums.order.transfer.PurchaseRequestEnum;
import com.authine.cloudpivot.ext.service.TransferPurchaseVoucherService;
import com.authine.cloudpivot.ext.utils.BoServiceUtils;
import com.authine.cloudpivot.ext.utils.JdbcTemplateUtils;
import com.authine.cloudpivot.ext.utils.TransferFinanceUtil;
import com.authine.cloudpivot.ext.utils.system.SessionUser;
import com.authine.hermes.app.launcher.service.ApplicationService;
import com.authine.mvp.app.launcher.dto.bo.query.ListBOQuery;
import com.authine.mvp.app.launcher.dto.bo.response.BO;
import com.authine.mvp.app.launcher.dto.bo.response.BOList;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.util.Assert;

import javax.ws.rs.POST;
import javax.ws.rs.Path;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.authine.hermes.app.launcher.service.ApplicationServiceFoundation.CUSTOM_SERVICE;

/**
 * 转采财务 付款
 *
 * @Author: liwei
 * @DateTime: 2021/8/3
 * @Description: TODO
 */
@Path("TransferFinancePaymentController")
@Slf4j
public class TransferFinancePaymentController extends ApplicationService {


    //金蝶生成凭证服务
    private TransferPurchaseVoucherService transferPurchaseVoucherService = new TransferPurchaseVoucherService();



    @Path("transferConfirmPayment")
    @POST
        @Operation(summary = "转采财务/采购付款/确认付款", tags = CUSTOM_SERVICE)
    public SingleResponse transferConfirmPayment(@Parameter TransferConfirmPaymentDto paymentDto) {
        Assert.notNull(paymentDto, "transferConfirmPayment 入参不能为空 ");

        //todo 涉及表数据比较多 需要添加事务控制
//        前置条件:
//        1.关联查询t_member_purchase_order,t_member_purchase_order.pay_account_id(淘宝付款账户)，若为空的可以一起付款，若不为空且必须一致，才能申请付款。
//        2.关联付款单状态t_purchase_request_payment.status=(待付款)
//        3.弹出付款表单，付款时间默认是当前日期，若付款方式是淘宝，支付方式=支付宝，
//        付款账户=t_member_purchase_order.pay_account_id查询t_pay_account对应付款账户名称,
//        若不为淘宝,需要根据当前登录人查询t_member_bank_account对应维护的个人付款账户,表单显示默认账户,可下拉选择其他账户,不能为空。
        SessionUser sessionUser = new SessionUser();
        if (null == sessionUser.get()) throw new BizException("未获取到登录信息!");
        String bankNumber = "";

        List<KingDeeRequestPayment> kingDeeRequestPaymentList = new ArrayList<>();

        //获取 采购付款单数据
        List<Map<String, Object>> purchaseRequestPayments = JdbcTemplateUtils.builder(ModelConst.T_PURCHASE_REQUEST_PAYMENT)
                .selectField("*").in("id", paymentDto.getIds()).queryForList();

        Assert.isTrue(null != purchaseRequestPayments && purchaseRequestPayments.size() > 0, "未找到付款单数据");

        if (null != paymentDto.getMemberBankId() && null != paymentDto.getAliPayNo()) {

            //systemManagement 获取支付宝账号 account
            Map<String, Object> payAccount = JdbcTemplateUtils.builder(ModelConst.T_PAY_ACCOUNT)
                    .selectField("*").eq("id", paymentDto.getAliPayNo()).queryForMap();

            if (null != payAccount) {
                bankNumber = String.valueOf(payAccount.get("account"));
            }
        } else {
            //userCenter 获取会员银行账号 bank_no
            Map<String, Object> bankAccount = JdbcTemplateUtils.builder(AppConst.PERSONAL_CENTER, ModelConst.T_MEMBER_BANK_ACCOUNT)
                    .selectField("*").eq("id", paymentDto.getMemberBankId()).queryForMap();

            if (null != bankAccount) {
                bankNumber = String.valueOf(bankAccount.get("bank_no"));
            }
        }
//        处理逻辑:
//        根据付款单id,查询t_purchase_request_payment,更新
//        1.付款单状态t_purchase_request_payment.status=财务确认
//        2.财务确认人t_purchase_request_payment.financial_name为当前操作人
//        3.财务确认时间
//        t_purchase_request_payment.financial_confirm_time为当前操作时间
//        4. 付款方式t_purchase_request_payment.payment_type
//        5. 付款账号t_purchase_request_payment.bank_number
//        6. 财务确认人id
//        t_purchase_request_payment.financial_confirmer_id为当前操作人id
//        相关调用:
//        调用金蝶生成转采付款凭证
//
//        确认付款之后，付款单状态修改为：财务已确认，回填财务确认人、财务确认时间字段
        for (Map<String, Object> purchaseRequestPayment : purchaseRequestPayments) {
            String status = String.valueOf(purchaseRequestPayment.get("purchase_payment_status"));
            //判断付款单状态  只有待财务确认状态的付款单才能付款
            if (!PurchaseRequestEnum.get(Integer.valueOf(status)).equals(PurchaseRequestEnum.PAYMENT)) {
                return SingleResponse.error(ErrorCodeConst.FINANCE_TRANSFER_MANAGEMENT_PAYMENT, "只有 待财务确认状态 的付款单才能付款");
            }

            String vendorId = "";
            String vendorName = "";
            String accountName = "";

            //金蝶请求参数集合数据
            List<KingDeeRequestPaymentDetail> kingDeeRequestPaymentDetails = new ArrayList<>();

            //获取 付款单详情  根据付款单 id 获取对应付款单明细
            List<Map<String, Object>> purchaseRequestPaymentDetails = JdbcTemplateUtils.builder(ModelConst.T_PURCHASE_REQUEST_PAYMENT_DETAIL)
                    .selectField("*").eq("payment_id", String.valueOf(purchaseRequestPayment.get("id"))).queryForList();

            Assert.isTrue(null != purchaseRequestPaymentDetails && purchaseRequestPaymentDetails.size() > 0, "未找到付款单明细数据");

            //遍历详情数据
            for (Map<String, Object> purchaseRequestPaymentDetail : purchaseRequestPaymentDetails) {

                Map<String, Object> purchaseRequestPaymentDetailParam = new HashMap<>();
                //付款请详情 付款状态
                purchaseRequestPaymentDetailParam.put("payment_detail_status", PurchaseRequestEnum.PAYED.id);
                //付款单详情 财务确认时间
                purchaseRequestPaymentDetailParam.put("financial_confirm_time", paymentDto.getFinancialConfirmTime());
                purchaseRequestPaymentDetailParam.put("id", purchaseRequestPaymentDetail.get("id"));

                //获取 会员采购订单 数据
                Map<String, Object> orderMap = JdbcTemplateUtils.builder(ModelConst.T_MEMBER_PURCHASE_ORDER)
                        .selectField("*").eq("id", String.valueOf(purchaseRequestPaymentDetail.get("member_purchase_order_id"))).queryForMap();

                Assert.notNull(orderMap, "未找到会员采购订单数据");

                //获取订单 未付金额
                BigDecimal noPaymentAmount = new BigDecimal(String.valueOf(orderMap.get("no_payment_amount")));
                //获取订单 采购总价
                BigDecimal paymentAmount = new BigDecimal(String.valueOf(orderMap.get("purchase_amount")));

                Map<String, Object> orderMapParam = new HashMap<>();
                if (noPaymentAmount.compareTo(BigDecimal.ZERO) == 0) {

                    orderMapParam.put("member_purchase_order_status", MemberPurchaseOrderEnum.PAYED.id);

                } else if (paymentAmount.compareTo(BigDecimal.ZERO) != 0 && noPaymentAmount.compareTo(paymentAmount) == -1) {

                    orderMapParam.put("member_purchase_order_status", MemberPurchaseOrderEnum.PARTIAL.id);
                }
                orderMapParam.put("id", orderMap.get("id"));

                //更新会员订单表  回写订单状态
                SingleResponse<BO> updatePurchaseOrder = BoServiceUtils.updateMainBo(ModelConst.T_MEMBER_PURCHASE_ORDER, orderMapParam);
                Assert.isTrue(updatePurchaseOrder.isSuccess(), "会员采购订单 回写状态失败！！！");

                SingleResponse<BO> updatePurchaseRequestPaymentDetail = BoServiceUtils.updateMainBo(ModelConst.T_PURCHASE_REQUEST_PAYMENT_DETAIL, purchaseRequestPaymentDetailParam);
                Assert.isTrue(updatePurchaseRequestPaymentDetail.isSuccess(), "付款单明细 回写状态失败！！！");

                accountName = String.valueOf(orderMap.get("platform_name"));
                vendorName = String.valueOf(orderMap.get("vendor_name"));

                // 根据 供应商名称 获取 转采供应商 id 对应金蝶那边的记录id
                vendorId = TransferFinanceUtil.getKingdeeOrgId(vendorName);


                KingDeeRequestPaymentDetail kingDeeRequestPaymentDetail = new KingDeeRequestPaymentDetail();

                kingDeeRequestPaymentDetail.setPoCode(String.valueOf(orderMap.get("po_code")));
                //此处的供应商 id 为 t_transfer_vendor 转采供应商表id ，分别对应京东 & 淘宝供应商，因为需要构建金蝶凭证业务逻辑，此处需要写死
                String pVendorId = String.valueOf(purchaseRequestPayment.get("vendor_id"));
                if (pVendorId.equals("16") || pVendorId.equals("124")) {
                    kingDeeRequestPaymentDetail.setPaymentDetailAmount(new BigDecimal(String.valueOf(purchaseRequestPaymentDetail.get("payment"))));
                }

                kingDeeRequestPaymentDetails.add(kingDeeRequestPaymentDetail);
            }

            Map<String, Object> purchaseRequestPaymentParam = new HashMap<>();
            //更新对应的 付款单 数据
            // 付款单状态
            purchaseRequestPaymentParam.put("purchase_payment_status", PurchaseRequestEnum.PAYED.id);
            //财务确认id
            purchaseRequestPaymentParam.put("financial_confirmer_id",  sessionUser.getUserFormat());
            //付款类型
            purchaseRequestPaymentParam.put("payment_type", paymentDto.getPaymentApplyType().id);
            //财务确认时间
            purchaseRequestPaymentParam.put("financial_confirm_time", paymentDto.getFinancialConfirmTime());
            //财务名字
            purchaseRequestPaymentParam.put("financial_name", RequestContext.getLoginName());
            //付款账号 回写
            purchaseRequestPaymentParam.put("bank_number", bankNumber);
            purchaseRequestPaymentParam.put("id", purchaseRequestPayment.get("id"));

            //更新 付款单数据
            SingleResponse<BO> updatePurchaseRequestPayment = BoServiceUtils.updateMainBo(ModelConst.T_PURCHASE_REQUEST_PAYMENT, purchaseRequestPaymentParam);
            Assert.isTrue(updatePurchaseRequestPayment.isSuccess(), "付款单 回写状态失败！！！");

            //封装金蝶请求参数
            KingDeeRequestPayment kingDeeRequestPayment = new KingDeeRequestPayment();
            kingDeeRequestPayment.setId(String.valueOf(purchaseRequestPayment.get("Id")));
            kingDeeRequestPayment.setBankNumber(bankNumber);
            kingDeeRequestPayment.setPaymentAmount(new BigDecimal(String.valueOf(purchaseRequestPayment.get("payment_amount"))));

            KingDeePaymentApplyType kingDeePaymentApplyType = KingDeePaymentApplyType.get(paymentDto.getPaymentApplyType().id);
            kingDeeRequestPayment.setInvoiceApplyTypeEnum(kingDeePaymentApplyType);

            kingDeeRequestPayment.setFinancialConfirmTime(paymentDto.getFinancialConfirmTime());
            kingDeeRequestPayment.setKingDeeRequestPaymentDetailList(kingDeeRequestPaymentDetails);
            kingDeeRequestPayment.setVendorId(vendorId);
            kingDeeRequestPayment.setAccountName(accountName);
            kingDeeRequestPayment.setTransferVendorName(vendorName);

            kingDeeRequestPaymentList.add(kingDeeRequestPayment);

        }

        try {
            //确认付款生成凭证
            transferPurchaseVoucherService.paymentCredentialGeneration(kingDeeRequestPaymentList);
        } catch (Exception e) {
            log.error("转采付款生成凭证异常 message:{} \n stackTrace:{}", ExceptionUtils.getMessage(e), ExceptionUtils.getStackTrace(e));
        }

        log.info("confirmPayment");
        return SingleResponse.buildSuccess();
    }


    @Path("transferRejectPayment")
    @POST
    @Operation(summary = "转采财务/采购付款/驳回", tags = CUSTOM_SERVICE)
    public SingleResponse transferRejectPayment(@Parameter List<String> idList) {

        Assert.isTrue(null != idList && idList.size() > 0, "转采财务 采购付款 驳回id集合不能为空");

        //获取 采购付款单数据
        List<Map<String, Object>> purchaseRequestPayments = JdbcTemplateUtils.builder(ModelConst.T_PURCHASE_REQUEST_PAYMENT)
                .selectField("*").in("id", idList).queryForList();

        Assert.isTrue(null != purchaseRequestPayments && purchaseRequestPayments.size() > 0, "未找到付款单数据");

        for (Map<String, Object> purchaseRequestPayment : purchaseRequestPayments) {

            String status = String.valueOf(purchaseRequestPayment.get("purchase_payment_status"));
            //判断付款单状态  只有待财务确认状态的付款单才能驳回
            if (!PurchaseRequestEnum.get(Integer.valueOf(status)).equals(PurchaseRequestEnum.PAYMENT)) {
                return SingleResponse.error(ErrorCodeConst.FINANCE_TRANSFER_MANAGEMENT_PAYMENT, "只有 待财务确认状态 的付款单才能驳回");
            }

            //获取 付款单详情  根据付款单 id 获取对应付款单明细
            List<Map<String, Object>> purchaseRequestPaymentDetails = JdbcTemplateUtils.builder(ModelConst.T_PURCHASE_REQUEST_PAYMENT_DETAIL)
                    .selectField("*").eq("payment_id", String.valueOf(purchaseRequestPayment.get("id"))).queryForList();

            Assert.isTrue(null != purchaseRequestPaymentDetails && purchaseRequestPaymentDetails.size() > 0, "未找到付款单明细数据");

            for (Map<String, Object> purchaseRequestPaymentDetail : purchaseRequestPaymentDetails) {

                //
                Map<String, Object> purchaseRequestPaymentDetailParam = new HashMap<>();
                purchaseRequestPaymentDetailParam.put("payment_detail_status", PurchaseRequestEnum.FINANCE_DISMISSAL.id);
                purchaseRequestPaymentDetailParam.put("id", purchaseRequestPaymentDetail.get("id"));

                //获取 会员采购订单 数据
                Map<String, Object> orderMap = JdbcTemplateUtils.builder(ModelConst.T_MEMBER_PURCHASE_ORDER)
                        .selectField("*").eq("id", String.valueOf(purchaseRequestPaymentDetail.get("member_purchase_order_id"))).queryForMap();

                Assert.isTrue(null != orderMap && !orderMap.isEmpty(), "未找到会员采购订单数据");

                BigDecimal noPayment = new BigDecimal(String.valueOf(orderMap.get("no_payment_amount")));
                BigDecimal payment = new BigDecimal(String.valueOf(purchaseRequestPaymentDetail.get("payment")));
                Map<String, Object> orderMapParam = new HashMap<>();
                orderMapParam.put("member_purchase_order_status", MemberPurchaseOrderEnum.PAYMENT.id);
                orderMapParam.put("no_payment_amount", noPayment.add(payment));
                orderMapParam.put("is_return_payment", true);
                orderMapParam.put("id", orderMap.get("id"));

                //更新会员订单表  回写订单状态
                SingleResponse<BO> updatePurchaseOrder = BoServiceUtils.updateMainBo(ModelConst.T_MEMBER_PURCHASE_ORDER, orderMapParam);
                Assert.isTrue(updatePurchaseOrder.isSuccess(), "会员采购订单 回写状态失败！！！");
                //更新 付款单详情
                SingleResponse<BO> updatePurchaseRequestPaymentDetail = BoServiceUtils.updateMainBo(ModelConst.T_PURCHASE_REQUEST_PAYMENT_DETAIL, purchaseRequestPaymentDetailParam);
                Assert.isTrue(updatePurchaseRequestPaymentDetail.isSuccess(), "付款单明细 回写状态失败！！！");

            }

            Map<String, Object> purchaseRequestPaymentParam = new HashMap<>();
            purchaseRequestPaymentParam.put("purchase_payment_status", PurchaseRequestEnum.FINANCE_DISMISSAL.id);
            purchaseRequestPaymentParam.put("id", purchaseRequestPayment.get("id"));

            //更新 付款单数据
            SingleResponse<BO> updatePurchaseRequestPayment = BoServiceUtils.updateMainBo(ModelConst.T_PURCHASE_REQUEST_PAYMENT, purchaseRequestPaymentParam);
            Assert.isTrue(updatePurchaseRequestPayment.isSuccess(), "付款单 回写状态失败！！！");

        }

        log.info("rejectPayment");
        return SingleResponse.buildSuccess();
    }


    @Path("transferCancelPayment")
    @POST
    @Operation(summary = "转采财务/采购付款/取消", tags = CUSTOM_SERVICE)
    public SingleResponse transferCancelPayment(@Parameter List<String> idList) {

        Assert.isTrue(null != idList && idList.size() > 0, "转采财务 采购付款 取消id集合不能为空");

        //获取 采购付款单数据
        List<Map<String, Object>> purchaseRequestPayments = JdbcTemplateUtils.builder(ModelConst.T_PURCHASE_REQUEST_PAYMENT)
                .selectField("*").in("id", idList).queryForList();

        Assert.isTrue(null != purchaseRequestPayments && purchaseRequestPayments.size() > 0, "未找到付款单数据");

        List<KingDeeCancelPayment> kingDeeCancelPaymentList = new ArrayList<>();

        List<Map<String, Object>> purchaseRequestPaymentParams = new ArrayList<>();
        for (Map<String, Object> purchaseRequestPayment : purchaseRequestPayments) {
            String status = String.valueOf(purchaseRequestPayment.get("purchase_payment_status"));
            //判断付款单状态  只有待财务确认状态的付款单才能取消
            if (!PurchaseRequestEnum.get(Integer.valueOf(status)).equals(PurchaseRequestEnum.PAYED)) {
                return SingleResponse.error(ErrorCodeConst.FINANCE_TRANSFER_MANAGEMENT_PAYMENT, "只有 财务确认状态 的付款单才能取消");
            }

            //获取 付款单详情  根据付款单 id 获取对应付款单明细
            List<Map<String, Object>> purchaseRequestPaymentDetails = JdbcTemplateUtils.builder(ModelConst.T_PURCHASE_REQUEST_PAYMENT_DETAIL)
                    .selectField("*").eq("payment_id", String.valueOf(purchaseRequestPayment.get("id"))).queryForList();

            Assert.isTrue(null != purchaseRequestPaymentDetails && purchaseRequestPaymentDetails.size() > 0, "未找到付款单明细数据");

            List<Map<String, Object>> purchaseRequestPaymentDetailParams = new ArrayList<>();
            for (Map<String, Object> purchaseRequestPaymentDetail : purchaseRequestPaymentDetails) {

                Map<String, Object> purchaseRequestPaymentDetailParam = new HashMap<>();
                purchaseRequestPaymentDetailParam.put("financial_confirm_time", null);
                purchaseRequestPaymentDetailParam.put("payment_detail_status", PurchaseRequestEnum.PAYMENT.id);
                purchaseRequestPaymentDetailParam.put("id", purchaseRequestPaymentDetail.get("id"));
                purchaseRequestPaymentDetailParams.add(purchaseRequestPaymentDetailParam);

                //需要获取订单 平台名称
                //获取 会员采购订单 数据
                Map<String, Object> orderMap = JdbcTemplateUtils.builder(ModelConst.T_MEMBER_PURCHASE_ORDER)
                        .selectField("*").eq("id", String.valueOf(purchaseRequestPaymentDetail.get("member_purchase_order_id"))).queryForMap();

                Assert.isTrue(null != orderMap && !orderMap.isEmpty(), "未找到会员采购订单数据");

            }

            //更新 付款单详情
            SingleResponse<BO> purchaseRequestPaymentDetailRes = BoServiceUtils.updateMainBo(ModelConst.T_PURCHASE_REQUEST_PAYMENT_DETAIL, purchaseRequestPaymentDetailParams);
            Assert.isTrue(purchaseRequestPaymentDetailRes.isSuccess(), " 付款单明细 状态回写失败！！！");

            Map<String, Object> purchaseRequestPaymentParam = new HashMap<>();
            purchaseRequestPaymentParam.put("financial_confirm_time", null);
            purchaseRequestPaymentParam.put("financial_name", null);
            purchaseRequestPaymentParam.put("financial_confirmer_id", null);
            purchaseRequestPaymentParam.put("payment_type", null);
            purchaseRequestPaymentParam.put("bank_number", null);
            purchaseRequestPaymentParam.put("purchase_payment_status", PurchaseRequestEnum.PAYMENT.id);
            purchaseRequestPaymentParam.put("id", purchaseRequestPayment.get("id"));
            purchaseRequestPaymentParams.add(purchaseRequestPaymentParam);

            KingDeeCancelPayment cancelPayment = new KingDeeCancelPayment();
            cancelPayment.setAccountName(String.valueOf(purchaseRequestPayment.get("id")));
            cancelPayment.setAccountName(String.valueOf(purchaseRequestPaymentDetails.get(0).get("platform_name")));

            kingDeeCancelPaymentList.add(cancelPayment);
        }

        // 更新 付款单
        SingleResponse<BO> purchaseRequestPaymentRes = BoServiceUtils.updateMainBo(ModelConst.T_PURCHASE_REQUEST_PAYMENT, purchaseRequestPaymentParams);
        Assert.isTrue(purchaseRequestPaymentRes.isSuccess(), " 付款单 状态回写失败！！！");

        //调用金蝶 转采取消付款凭证
        try {
            transferPurchaseVoucherService.cancelPaymentDeletionVoucher(kingDeeCancelPaymentList);
        } catch (Exception e) {
            log.error("转采取消付款凭证 message:{} \n stackTrace:{}", ExceptionUtils.getMessage(e), ExceptionUtils.getStackTrace(e));
        }

        log.info("cancelPayment");
        return SingleResponse.buildSuccess();
    }


    @Path("transferUpdateConfirmPayment")
    @POST
    @Operation(summary = "转采财务/采购付款/修改确认时间", tags = CUSTOM_SERVICE)
    public SingleResponse transferUpdateConfirmPayment(@Parameter UpdateConfirmTimeDto updateConfirmTimeDto) {

        Assert.notNull(updateConfirmTimeDto, "transferUpdateConfirmPayment 入参不能为空 ");

        //获取 采购付款单数据
        List<Map<String, Object>> purchaseRequestPayments = JdbcTemplateUtils.builder(ModelConst.T_PURCHASE_REQUEST_PAYMENT)
                .selectField("*").in("id", updateConfirmTimeDto.getIds()).queryForList();

        Assert.isTrue(null != purchaseRequestPayments && purchaseRequestPayments.size() > 0, "未找到付款单数据");

        for (Map<String, Object> purchaseRequestPayment : purchaseRequestPayments) {

            String status = String.valueOf(purchaseRequestPayment.get("purchase_payment_status"));
            //判断付款单状态  只有待财务确认状态的付款单才能修改确认时间
            if (!PurchaseRequestEnum.get(Integer.valueOf(status)).equals(PurchaseRequestEnum.PAYED)) {
                return SingleResponse.error(ErrorCodeConst.FINANCE_TRANSFER_MANAGEMENT_PAYMENT, "只有 财务确认状态 的付款单才能修改确认时间");
            }

            Map<String, Object> purchaseRequestPaymentParam = new HashMap<>();
            purchaseRequestPaymentParam.put("financial_confirm_time", updateConfirmTimeDto.getConfirmTime());
            purchaseRequestPaymentParam.put("id", purchaseRequestPayment.get("id"));

            //获取 付款单详情  根据付款单 id 获取对应付款单明细
            List<Map<String, Object>> purchaseRequestPaymentDetails = JdbcTemplateUtils.builder(ModelConst.T_PURCHASE_REQUEST_PAYMENT_DETAIL)
                    .selectField("*").eq("payment_id", String.valueOf(purchaseRequestPayment.get("id"))).queryForList();

            Assert.isTrue(null != purchaseRequestPaymentDetails && purchaseRequestPaymentDetails.size() > 0, "未找到付款单明细数据");

            String orgOrTransfer = "";
            String vendorName = "";
            String accountName = "";

            List<KingDeeRequestPaymentDetail> kingDeeRequestPaymentDetailList = new ArrayList<>();

            for (Map<String, Object> purchaseRequestPaymentDetail : purchaseRequestPaymentDetails) {
                Map<String, Object> purchaseRequestPaymentDetailParam = new HashMap<>();
                purchaseRequestPaymentDetailParam.put("financial_confirm_time", updateConfirmTimeDto.getConfirmTime());
                purchaseRequestPaymentDetailParam.put("id", purchaseRequestPaymentDetail.get("id"));

                //更新 付款单详情
                SingleResponse<BO> updatePurchaseRequestPaymentDetail = BoServiceUtils.updateMainBo(ModelConst.T_PURCHASE_REQUEST_PAYMENT_DETAIL, purchaseRequestPaymentDetailParam);
                Assert.isTrue(updatePurchaseRequestPaymentDetail.isSuccess(), "付款单明细 回写状态失败！！！");

                //获取 会员采购订单 数据
                Map<String, Object> orderMap = JdbcTemplateUtils.builder(ModelConst.T_MEMBER_PURCHASE_ORDER)
                        .selectField("*").eq("id", String.valueOf(purchaseRequestPaymentDetail.get("member_purchase_order_id"))).queryForMap();

                if (null == orderMap || orderMap.isEmpty()) {
                    return SingleResponse.error(ErrorCodeConst.FINANCE_TRANSFER_MANAGEMENT_PAYMENT, "未找到会员采购订单数据");

                }

                accountName = String.valueOf(orderMap.get("platform_name"));
                vendorName = String.valueOf(orderMap.get("vendor_name"));
                orgOrTransfer = TransferFinanceUtil.getKingdeeOrgId(vendorName);

                KingDeeRequestPaymentDetail kingDeeRequestPaymentDetail = new KingDeeRequestPaymentDetail();

                kingDeeRequestPaymentDetail.setPoCode(String.valueOf(orderMap.get("po_code")));

                kingDeeRequestPaymentDetailList.add(kingDeeRequestPaymentDetail);

            }

            // 更新 付款单
            SingleResponse<BO> purchaseRequestPaymentRes = BoServiceUtils.updateMainBo(ModelConst.T_PURCHASE_REQUEST_PAYMENT, purchaseRequestPaymentParam);
            Assert.isTrue(purchaseRequestPaymentRes.isSuccess(), " 付款单 状态回写失败！！！");

            //封装金蝶请求参数
            KingDeeRequestPayment kingDeeRequestPayment = new KingDeeRequestPayment();
            kingDeeRequestPayment.setId(String.valueOf(purchaseRequestPayment.get("id")));
            kingDeeRequestPayment.setBankNumber(String.valueOf(purchaseRequestPayment.get("bank_number")));
            kingDeeRequestPayment.setPaymentAmount(new BigDecimal(String.valueOf(purchaseRequestPayment.get("payment_amount"))));

            KingDeePaymentApplyType kingDeePaymentApplyType = KingDeePaymentApplyType.get(Integer.valueOf(String.valueOf(purchaseRequestPayment.get("payment_type"))));
            kingDeeRequestPayment.setInvoiceApplyTypeEnum(kingDeePaymentApplyType);

            kingDeeRequestPayment.setFinancialConfirmTime(updateConfirmTimeDto.getConfirmTime());
            kingDeeRequestPayment.setKingDeeRequestPaymentDetailList(kingDeeRequestPaymentDetailList);
            kingDeeRequestPayment.setVendorId(orgOrTransfer);
            kingDeeRequestPayment.setAccountName(accountName);
            kingDeeRequestPayment.setTransferVendorName(vendorName);

            try {
                //修改付款时间生成凭证
                transferPurchaseVoucherService.modifyPaymentTimeVoucher(kingDeeRequestPayment);
            } catch (Exception e) {
                log.error("转采修改付款时间生成凭证异常 message:{} \n stackTrace:{}", ExceptionUtils.getMessage(e), ExceptionUtils.getStackTrace(e));
            }
        }

        log.info("updateConfirmPayment");
        return SingleResponse.buildSuccess();
    }


    /**
     * 获取对应的银行付款账号 页面使用
     */
    @Path("getCurrentBankInfo")
    @POST
    @Operation(summary = "转采财务/采购付款/页面获取当前用户银行账户tree", tags = CUSTOM_SERVICE)
    public List<TreeData> getCurrentBankInfo() {

        ListBOQuery listQry = new ListBOQuery();
        listQry.setPageIndex(-1);
        listQry.setSchemaCode(ModelConst.T_MEMBER_BANK_ACCOUNT);

        SingleResponse<BOList> response = boService.list(listQry);

        if (null == response || null == response.getData().getData()) {
            log.error(" 未找到银行账号信息 ！！！");
            return null;
        }

        List<Map<String, Object>> data = response.getData().getData();

        //根据 账号分组
        Map<String, List<Map<String, Object>>> accountMap = data.stream().collect(Collectors.groupingBy(e -> String.valueOf(e.get("bank_account"))));

        log.info("分组之后的 map accountMap:{}", accountMap);
        List<TreeData> treeDataList = new ArrayList<>();

        for (String key : accountMap.keySet()) {
            TreeData treeData = new TreeData();
            treeData.setTitle(key);
            treeData.setKey("");
            List<TreeData> children = new ArrayList<>();
            for (Map<String, Object> map : accountMap.get(key)) {
                TreeData child = new TreeData();
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.append(map.get("id"));
                stringBuilder.append("=");
                stringBuilder.append(map.get("bank_no"));
                child.setKey(stringBuilder.toString());
                child.setTitle(String.valueOf(map.get("bank_no")));
                children.add(child);
            }
            treeData.setChildren(children);
            treeDataList.add(treeData);
        }
        log.info("treeDataList:{}", treeDataList);
        return treeDataList;
    }


}
